package db

import (
	"fmt"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var DB *gorm.DB

var NewDB *gorm.DB

// 初始化db
func SetupDb() {
	var dsn = fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s",
		"192.168.3.132",
		"postgres",
		"root",
		"testdb",
		5432,
		"disable",
		"Asia/Shanghai")

	var err error
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // Slow SQL threshold
			LogLevel:      logger.Info, // Log level
			Colorful:      false,       // Disable color
		},
	)
	DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		panic(err)
	}

	setConnectionPool(DB)
	err = DB.AutoMigrate(&Table{})
	if err != nil {
		panic(err)
	}
	err = DB.AutoMigrate(&Column{})
	if err != nil {
		panic(err)
	}
	err = DB.AutoMigrate(&System{})
	if err != nil {
		panic(err)
	}

	// 新表的库初始化
	var newDsn = fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s",
		"192.168.3.132",
		"postgres",
		"root",
		"vehicle",
		5432,
		"disable",
		"Asia/Shanghai")
	newLogger2 := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // Slow SQL threshold
			LogLevel:      logger.Info, // Log level
			Colorful:      false,       // Disable color
		},
	)
	NewDB, err = gorm.Open(postgres.Open(newDsn), &gorm.Config{Logger: newLogger2})
	if err != nil {
		panic(err)
	}

}

// 设置连接处
func setConnectionPool(db *gorm.DB) {
	sqlDB, err := db.DB()

	if err != nil {
		panic(err)
	}

	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)
}

// 维护表结构
func autoMigrate() {
	err := DB.AutoMigrate(&Table{})
	if err != nil {
		panic(err)
	}
	err = DB.AutoMigrate(&Column{})
	if err != nil {
		panic(err)
	}
	err = DB.AutoMigrate(&System{})
	if err != nil {
		panic(err)
	}
}
